const app = getApp()
import Toast from '@vant/weapp/toast/toast';
import Dialog from '@vant/weapp/dialog/dialog';

import {
  reqCreateWxPayment,
  reqWxUserInfo,
  reqBindWx,
  reqQueryPayStatus
} from '../../../../../request/api.js'

Page({
  data: {
    navHeight: app.globalData.navHeight + 'px', //头部距离
    bottomHeight: app.globalData.bottomHeight + 'px', //iphone底部距离
    srcMusicBg: '/statics/images/onlineMusic.png',
    deviceImg: '/statics/images/yjt.png',

    currentTab: 0,


    imei: "",
    chooseList: [{
        id: 1,
        time: '一个月',
        money: app.globalData.monthPrice,
        active: false,
        value: 1,
      },
      {
        id: 2,
        time: '三个月',
        money: app.globalData.quarterPrice,
        active: false,
        value: 2,
      },
      {
        id: 3,
        time: '半年',
        money: app.globalData.halfYear,
        active: false,
        value: 3,
      },
      {
        id: 4,
        time: '一年',
        money: app.globalData.yearPrice,
        active: false,
        value: 4,
      },
    ],
    choseIndex: 0,
    totalMoney: app.globalData.monthPrice,
    agreementRadio: false,
    stepperValue: 1,
    serviceState: "",
    serviceTime: "",
    inDate: "",
    currentOrderNo: "", // 用来支付完成后判断跳转详情页面

  },
  onLoad(e) {
    if (e.imei) {
      this.data.chooseList[0].active = true
      this.setData({
        imei: e.imei,
        serviceTime: e.serviceTime,
        serviceState: e.serviceState,
        inDate: e.inDate,
        chooseList: this.data.chooseList,
        choseIndex: 0,
        totalMoney: app.globalData.monthPrice,
        openId: app.globalData.openId || '',
        appOpenId: app.globalData.openId || '', // 用于判断提示词的显隐
      })
      if (app.globalData.openId) {
        this.setData({
          currentOpenId: app.globalData.openId
        })
        app.globalData.currentOpenId = app.globalData.openId
      }
    }
  },
  swichNav(e) {
    let {
      current
    } = e.currentTarget.dataset
    this.setData({
      currentTab: current
    })
  },
  bindChangeTab(e) {
    let {
      current
    } = e.detail
    this.setData({
      currentTab: current
    })
  },

  // 选择套餐
  onChoosePackage(e) {
    let {
      item
    } = e.currentTarget.dataset
    this.data.chooseList.forEach((choseItem, choseIndex) => {
      if (choseItem.id == item.id) {
        this.data.chooseList[choseIndex].active = true
        this.data.choseIndex = choseIndex
        this.data.totalMoney = this.data.stepperValue * this.data.chooseList[choseIndex].money
      } else {
        this.data.chooseList[choseIndex].active = false
      }
    })
    this.setData({
      chooseList: this.data.chooseList,
      choseIndex: this.data.choseIndex,
      totalMoney: this.formatNumber(this.data.totalMoney),
      stepperValue: 1,
    })
  },
  // 判断是否有小数，有的话取后两位
  formatNumber(num) {
    // 将数字转换为字符串
    let strNum = num.toString();
    // 分割整数部分和小数部分
    let [intPart, floatPart] = strNum.split('.');

    // 如果小数部分存在且长度超过2位，则只取前两位
    if (floatPart && floatPart.length > 2) {
      floatPart = floatPart.slice(0, 2);
      return parseFloat(intPart + '.' + floatPart);
    }

    // 如果没有小数部分，或者小数部分长度不超过2位，则直接返回原数字
    return num;
  },
  // 修改stepper值
  onChangeStepper(e) {
    this.setData({
      stepperValue: e.detail,
      totalMoney: this.formatNumber(e.detail * this.data.chooseList[this.data.choseIndex].money)
    })
  },
  // 选择事件
  radioChange(e) {
    this.setData({
      agreementRadio: !this.data.agreementRadio
    })
  },
  // 确认
  onConfirm() {
    if (!this.data.agreementRadio) {
      Dialog.confirm({
          title: '确认开通',
          message: '请您阅读并确认《付费服务协议》',
          confirmButtonText: "继续开通",
          cancelButtonText: "取消"
        })
        .then(() => {
          // on confirm
          this.setData({
            agreementRadio: true
          })
          if (app.globalData.openId) {

            this.createPayment()
          } else {
            this.getOpenId()
          }


        })
        .catch(() => {
          // on cancel
        });
    } else {
      this.createPayment()
    }
  },
  async createPayment() {
    let currentItem = this.data.chooseList[this.data.choseIndex]
    let currentOrderNo = this.generateOrderNumber()
    let res = await reqCreateWxPayment({
      customerOpenId: this.data.openId,
      // orderNo: currentOrderNo,
      username: wx.getStorageSync('username'),
      payWay: 1,
      amount: this.data.totalMoney,
      mobile: app.globalData.mobile,
      content: `在线音乐套餐(￥${currentItem.money}/${currentItem.time})`,
      imei: this.data.imei,
      inDate: currentItem.time == "年卡" ? this.data.stepperValue * 12 : currentItem.time == "季卡" ? this.data.stepperValue * 3 : this.data.stepperValue
    })
    if (res.code !== 20000) return Toast.fail(res.message);
    this.setData({
      currentOrderNo
    })

    // 用于判断支付成功页面跳转回来时的业务
    app.globalData.currentOrderNo = this.data.currentOrderNo
    app.globalData.currentOpenId = this.data.currentOpenId

    this.orderPay(res.data.data)
  },
  // 获取微信用户openId
  getOpenId() {
    let _this = this;
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    wx.login({
      async success(res) {
        if (res.code) {
          const res1 = await reqWxUserInfo({
            jsCode: res.code
          }) //获取信息
          if (res1.code !== 20000) {
            wx.hideLoading()
            showMsg(res1.message)
            return
          }
          console.log(res1, "res1")
          _this.setData({
            openId: res1.data.row.openid,
            currentOpenId: res1.data.row.openid,
          })
          _this.createPayment()
        } else {
          wx.hideLoading()
          console.log('绑定失败！')
        }
      }
    })
  },
  // 绑定微信
  onBind() {
    let that = this
    wx.showLoading({
      title: '绑定中...',
      mask: true
    })
    wx.getUserProfile({
      desc: '用于获取微信基本信息',
      success: async function (res) {
        let {
          nickName: wxNickName,
          avatarUrl: wxAvatar
        } = res.userInfo
        wx.login({
          async success(res) {
            if (res.code) {
              const res1 = await reqWxUserInfo({
                jsCode: res.code
              }) //获取信息
              if (res1.code !== 20000) {
                wx.hideLoading()
                showMsg(res1.message)
                return
              }
              let {
                row
              } = res1.data
              let params = {
                id: app.globalData.userId,
                openId: row.openid,
                wxNickName,
                wxAvatar
              }
              const res2 = await reqBindWx(params) //绑定微信
              if (res2.code !== 20000) {
                wx.hideLoading()
                Toast(res2.message)
                return
              }
              app.globalData.wxNickName = wxNickName
              wx.setStorageSync('wxNickName', wxNickName)
              app.globalData.wxAvatar = wxAvatar
              wx.setStorageSync('wxAvatar', wxAvatar)
              that.setData({
                wxNickName,
                wxAvatar,
                openId: row.openid,
                currentOpenId: row.openid,
              })
              app.globalData.openId = row.openid
              wx.setStorageSync('openId', row.openid) //微信openId
              wx.hideLoading()
              wx.showToast({
                title: '绑定成功',
              })
            } else {
              wx.hideLoading()
              console.log('绑定失败！')
            }
          }
        })

      },

      fail: function (err) {
        wx.hideLoading()
        console.log(err);
      }
    })
  },
  // 随机生成12位的订单号
  generateOrderNumber() {
    var chars = '0123456789';
    var orderNumber = '';
    for (var i = 0; i < 5; i++) {
      orderNumber += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    return orderNumber + Date.now().toString();
  },
  // 调起支付窗口
  orderPay(payInfo) {
    let _this = this;
    wx.requestPayment({
      'timeStamp': payInfo.timeStamp,
      'nonceStr': payInfo.nonceStr,
      'package': payInfo.packageVal,
      'signType': payInfo.signType,
      'paySign': payInfo.paySign,
      'success': function (res) {
        // 支付成功的回调
        app.globalData.currentOrderNo = _this.data.currentOrderNo
        // _this.onCheckState()
      },
      'fail': function (res) {
        app.globalData.currentOrderNo = ""
        _this.setData({
          currentOrderNo: ""
        })
        wx.showToast({
          title: '支付失败',
          icon: 'none',
          duration: 2000,
          mask: true
        })
      }
    })
  },
  // 查询状态
  async onCheckState() {
    console.log(this.data.currentOrderNo, "this.data.currentOrderNo")
    let res = await reqQueryPayStatus(this.data.currentOrderNo)
    if (res.code !== 20000) return Toast.fail(res.message);
    console.log(res, "res")
  },
  // 设备订单列表
  onDeviceOrders() {
    // wx.navigateTo({
    //     url: `/pages/deviceOrder/deviceOrder?imei=${this.data.imei}`,
    // })
    wx.navigateTo({
      url: '/pages/myOrder/myOrder',
    })
  },

  onHide() {
    // this.setData({
    //     currentOrderNo: "",
    //     currentOpenId: ""
    // })
    // app.globalData.currentOrderNo = ""
    // app.globalData.currentOpenId = ""

  }
})